package com.caojing.syby.httputils;

import com.caojing.syby.config.UrlConfig;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/*
* 封装得retrofit帮助类
* */
public class RetrofitHelper {

    /*
    * 定义retrofit帮助类用到得属性
    *
    * */
    /*
    * 类得实例*/
    private static RetrofitHelper instance;
    /*retrofit得实例*/
    public Retrofit retrofit;
    /*gson得实例，用于gson解析,可有可无*/
    public Gson gson;
    /*构造器*/
    private RetrofitHelper() {
    }
    /*retrofit帮助类得单利模式*/
    public static synchronized RetrofitHelper getInstance() {
        if (instance == null) {
            instance = new RetrofitHelper();
        }
        return instance;
    }
    /*retrofit访问网络第一步是用注解创建接口，此方法是根据接口得到接口对象
    * 然后就可以用接口对象去调用接口里得方法*/
    public <T> T createRetrofitService(Class<T> service) {
        if (retrofit == null) {
            createGson();
            initRetrofit();
        }
        return retrofit.create(service);
    }
    /*初始化retrofit*/
    private void initRetrofit() {
        retrofit = new Retrofit.Builder()
                .baseUrl(UrlConfig.Path.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }
    /*初始化gson,可有可无*/
    private void createGson() {
        gson = new GsonBuilder()
                .serializeNulls()
                .create();
    }

}